import { ChangeDetectorRef, Component } from '@angular/core';
import Peer, { DataConnection } from 'peerjs';

@Component({
  selector: 'app-root',
  template: `
    <input type="text" [(ngModel)]="peerId" placeholder="您的peerId">
    <button (click)="joinIn()">加入</button>
    <br>
    <input type="text" [(ngModel)]="otherPeerId" placeholder="其他人的peerId">
    <button (click)="connect()">建立链接</button>
    <br>
    <input type="text" [(ngModel)]="message">
    <button (click)="send()">发送</button>
    <br>
    <div>
      <p *ngFor="let item of list">{{item}}</p>
    </div>
  `,
  styles: [],
})
export class AppComponent {
  peerId = '';
  message = '';
  otherPeerId = '';
  peer?: Peer;
  conn?: DataConnection;
  list: any = [];

  constructor(
      private cdr: ChangeDetectorRef,
  ) {
  }

  joinIn() {
    let that = this;
    //这里是局域网ip，或者是外部可以访问的peer server ip
    this.peer = new Peer(this.peerId, {host: '172.16.1.152', port: 9000, path: '/myapp'});
    this.peer.on('open', args => {
      this.peerId = args;
      that.addLog(`初始化成功，peerId为:${this.peerId}`);
    });
    this.peer.on('error', e => {
      that.addLog(`初始化失败，错误信息：${e.message}`);

    });
    this.peer.on('connection', (conn) => {
      conn.on('data', function (data) {
        that.addLog(`收到<${conn.peer}>发来的消息:${data}`);
      });
    });
  }

  connect() {
    let that = this;
    this.conn = this.peer?.connect(this.otherPeerId);
    this.conn?.on('open', () => {
      that.addLog(`建立链接成功`);
    });
    this.conn?.on('error', (e) => {
      that.addLog(`建立链接失败，错误信息：${e.message}`);
    });
  }

  send() {
    this.conn?.send(this.message);
    this.message = '';
  }

  addLog(message: any) {
    console.log(message);
    this.list.push(message);
    //手动触发变更检查，防止页面刷新延迟
    this.cdr.detectChanges();
  }
}
